package com.jy.app.lib.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by jan on 2016/5/8.
 */
public class LogUtil {
    public static String tagPrefix = "";
    public static boolean showV = true;
    public static boolean showD = true;
    public static boolean showI = true;
    public static boolean showW = true;
    public static boolean showE = true;
    public static boolean showWTF = true;
    public static boolean enableWrite = true;

    /**
     * 得到tag（所在类.方法（L:行））
     * @return
     */
    private static String generateTag() {
        StackTraceElement stackTraceElement = Thread.currentThread().getStackTrace()[4];
        String callerClazzName = stackTraceElement.getClassName();
        callerClazzName = callerClazzName.substring(callerClazzName.lastIndexOf(".") + 1);
        String tag = "%s.%s(L:%d)";
        tag = String.format(tag, new Object[]{callerClazzName, stackTraceElement.getMethodName(), Integer.valueOf(stackTraceElement.getLineNumber())});
        //给tag设置前缀
        tag = TextUtils.isEmpty(tagPrefix) ? tag : tagPrefix + ":" + tag;
        return tag;
    }

    public static void v(String msg) {
        if (showV) {
            String tag = generateTag();
            Log.v(tag, msg);
        }
    }

    public static void v(String msg, Throwable tr) {
        if (showV) {
            String tag = generateTag();
            Log.v(tag, msg, tr);
        }
    }

    public static void d(String msg) {
        if (showD) {
            String tag = generateTag();
            Log.d(tag, msg);
        }
    }
    public static void dout(String msg) {
        if (showD) {
            String tag = generateTag();
            Log.d(tag, msg);
            if(enableWrite){
                writeLog(msg);
            }
        }
    }

    public static void d(String msg, Throwable tr) {
        if (showD) {
            String tag = generateTag();
            Log.d(tag, msg, tr);
        }
    }

    public static void i(String msg) {
        if (showI) {
            String tag = generateTag();
            Log.i(tag, msg);
        }
    }

    public static void i(String msg, Throwable tr) {
        if (showI) {
            String tag = generateTag();
            Log.i(tag, msg, tr);
        }
    }

    public static void w(String msg) {
        if (showW) {
            String tag = generateTag();
            Log.w(tag, msg);
        }
    }

    public static void w(String msg, Throwable tr) {
        if (showW) {
            String tag = generateTag();
            Log.w(tag, msg, tr);
        }
    }

    public static void e(String msg) {
        if (showE) {
            String tag = generateTag();
            Log.e(tag, msg);
        }
    }

    public static void e(String msg, Throwable tr) {
        if (showE) {
            String tag = generateTag();
            Log.e(tag, msg, tr);
        }
    }

    public static void wtf(String msg) {
        if (showWTF) {
            String tag = generateTag();
            Log.wtf(tag, msg);
        }
    }

    public static void wtf(String msg, Throwable tr) {
        if (showWTF) {
            String tag = generateTag();
            Log.wtf(tag, msg, tr);
        }
    }


    private static void writeLog(String msg){
        try{
            String path = Environment.getExternalStorageDirectory().getPath()+File.separator+"wytLog";
            File logFile = new File(path);
            if(!logFile.exists()){
                i("createNewFile1"+ logFile.mkdir());
            }
            logFile = new File(path+"/log");
            if(!logFile.exists()){
                i("createNewFile2"+ logFile.mkdir());
            }

            logFile = new File(path+"/log/log.txt");
            if(!logFile.exists()){
                i("createNewFile3"+ logFile.createNewFile());
            }
//            open(logFile.getAbsolutePath()).print(msg);
            String time = DateTimeUtils.dateToString(new Date(), DateTimeUtils.EnumDateFmt.yyyyMMddHHmmss);
            OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(path+"/log/log.txt",true),"UTF-8");
            osw.write("["+time+"] "+msg+"\n");
            osw.close();
        }
        catch(Exception e){
            e.printStackTrace();
            e(e.getLocalizedMessage(),e);
        }
    }


    private static LogUtil mLogWriter;

    private static String mPath;

    private static Writer mWriter;
    private LogUtil(String file_path) {
        this.mPath = file_path;
        this.mWriter = null;
    }
    private static SimpleDateFormat df;
    public static LogUtil open(String file_path) throws IOException {
        if (mLogWriter == null) {
            mLogWriter = new LogUtil(file_path);
        }
        File mFile = new File(mPath);
        mWriter = new BufferedWriter(new FileWriter(mPath), 2048);
        df = new SimpleDateFormat("[yy-MM-dd hh:mm:ss]: ");

        return mLogWriter;
    }

    public void close() throws IOException {
        mWriter.close();
    }

    public void print(String log) throws IOException {
        // 打开一个随机访问文件流，按读写方式
//        RandomAccessFile randomFile = new RandomAccessFile(mPath, "rw");

        FileWriter writer = new FileWriter("", true);
        writer.write(log);
        writer.close();

        // 文件长度，字节数
//        long fileLength = randomFile.length();
//        // 将写文件指针移到文件尾。
//        randomFile.seek(fileLength);
//        randomFile.writeBytes(log);
//        randomFile.close();
//        mWriter.write(df.format(new Date()));
//        mWriter.write(log);
//        mWriter.write("\n");
//        mWriter.flush();
    }

    public void print(Class cls, String log) throws IOException { //如果还想看是在哪个类里可以用这个方法
        mWriter.write(df.format(new Date()));
        mWriter.write(cls.getSimpleName() + " ");
        mWriter.write(log);
        mWriter.write("\n");
        mWriter.flush();
    }
}
